package com.cwx.interfaces.rong360.utils;


import com.alibaba.fastjson.JSON;
import com.cwx.interfaces.rong360.client.ClientManager;
import com.cwx.interfaces.rong360.client.RongClient;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author guocong
 *         Created by Administrator on 2016/3/31.
 */
public class RequestUtil {
	
    public static String request(String method, Map<String, Object> bizData, String appId, 
    		String privateKey, boolean isTestEnv) throws Exception {
    	if (StringUtils.isEmpty(method) || bizData.isEmpty()) {
    		throw new IllegalArgumentException("参数错误！method和biz_data不能为空！");
    	}
    	if (!isValidMethod(method)) {
    		throw new IllegalArgumentException("参数method格式错误！method格式应该为xxx.xxx.xxx.xxx");
    	}
        Map<String, String> params = new HashMap<>();
        params.put("method", method);
        params.put("biz_data", JSON.toJSONString(bizData));
        RongClient client = ClientManager.createClient(appId, privateKey, isTestEnv);
        return client.execute(params);
    }
    
    private static boolean isValidMethod(String method) {
    	String pattern = "\\w+\\.\\w+\\.\\w+\\.\\w+";
    	return Pattern.matches(pattern, method);
    }
    
}
